package com.lc.dmd.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.study.common.enums.DataSourceEnum;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: some desc
 * @author: LChuang
 * @date: 2023/9/6 14:32
 */
@Configuration
public class DataSourceConfig {

    static {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl("");
    }

    @Bean
    @ConfigurationProperties("spring.datasource.ds1")
    public DataSource ds1() {
        /*
        使用DataSource创建数据源yml文件中，数据库连接必须使用jdbc-url
        使用DruidDataSource创建数据源yml文件中，数据库连接必须使用url
         */
//        return DataSourceBuilder.create().build();
        return new DruidDataSource();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.ds2")
    public DataSource ds2() {
//        return DataSourceBuilder.create().build();
        return new DruidDataSource();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.ds3")
    public DataSource ds3() {
//        return DataSourceBuilder.create().build();
        return new DruidDataSource();
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource ds1, DataSource ds2,DataSource ds3) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceEnum.DS1.name(), ds1);
        targetDataSources.put(DataSourceEnum.DS2.name(), ds2);
        targetDataSources.put(DataSourceEnum.DS3.name(), ds3);
        return new DynamicDataSource(ds1, targetDataSources);
    }
}
